<template>
  <div id="app" class="box">
    <template v-if="fullscreen"> </template>
    <el-container v-else>
      <el-aside v-if="showactive" class="left"  style="background: #fafafa">
        <div style="padding: 10px; height: 100%; box-sizing: border-box">
          <div style="margin-bottom: 10px">
            <div style="margin-bottom: 10px">
              <el-select
                ref="itemSelect"
                v-model="choiceDatasourceId"
                @change="datasourceChangeEvents"
                size="small"
                filterable
                placeholder="请先选择数据源"
                style="width: 100%; margin-top: 10px"
              >
                <el-option
                  v-for="item in datasourceOptions"
                  :key="item.label"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </div>
          </div>

          <div style="overflow: auto; padding-bottom: 30px">
            <el-tree
              :draggable="true"
              @node-drag-start="handleDragStart"
              @node-drag-end="handleDragEnd"
              :props="defaultProps"
              :data="databaseList"
              :allow-drop="allowDrop"
              :allow-drag="allowDrag"
              @node-click="handleNodeClick"
              ref="databaseTree"
              highlight-current
              empty-text=""
              :default-expanded-keys="databaseExpandedKeys"
              node-key="id"
              @node-expand="handleNodeExpand"
              class="database-list-tree"
            >
              <span :class="data.icon" slot-scope="{ node, data }">
                <span v-if="data.needLoad"
                  ><i class="el-icon-loading"></i
                ></span>
                <span :title="data.description" v-else>
                  <span
                    :id="data.dbName"
                    v-if="data.type == 4"
                    style="margin-left: 20px"
                    @contextmenu.prevent="onTagContexmenu"
                    >{{ node.label }}</span
                  >
                  <span style="margin-left: 20px" v-else
                    >{{ node.label }}
                  </span>
                  <el-tooltip
                    v-if="!!data.comment"
                    effect="dark"
                    :content="data.comment"
                    placement="top-start"
                    :open-delay="600"
                  >
                    <span style="color: #aaa">-{{ data.comment }}</span>
                  </el-tooltip>
                </span>
              </span>
            </el-tree>
          </div>
        </div>
      </el-aside>
      <div v-if="showactive" class="resize" title="">
        ⋮
      </div>
      <el-container class="right">
        <el-main style="padding: 0 ;margin-top: 10px">
          <el-tabs v-if="showactive" type="card" closable
                   v-model="activePage"
                   @tab-click="changePage"
                   @tab-remove="removePageTab"
                   style="padding: 5px 10px 0" class="my-custom-cls">

            <el-tab-pane
                    :label="item.name"
                    :name="item.query.key"
                    :key="item.name"
                    v-for="item in currentPageList"
            >
              <sqlexcuter
                      ref="$sqlExcuter"
                      @loadDatasourceList="loadDatasourceList"
                      @initLoadDataList="initLoadDataList"
                      @setconfig="setcongig"  :choiceDatasourceId="choiceDatasourceId"  v-if="item.viewType==1" >

              </sqlexcuter>
              <sqltable v-if="item.viewType==2" :queryData="queryData"></sqltable>
              <sqldatabase  v-if="item.viewType==3" :queryData="queryData"> </sqldatabase>
            </el-tab-pane>
          </el-tabs>
          <manage v-else></manage>
        </el-main>
      </el-container>
    </el-container>

  </div>
</template>

<script>
import userApi from './common/api/user'
import datasourceApi from './common/api/datasource'
import $sqlExcuter from "./components/sqlExcutor/index";
export default {
  comments: { $sqlExcuter },
  data () {

    return {
      showactive:true,
      isCollapse: false,
      aboutDialogVisible: false,
      userSelfInfo: {},
      datasourceOptions: [],
      datasourceList: [],
      datasourceGroupList: [],
      choiceDatasourceId: "",
      choiceDatasourceGroup: "",
      defaultProps: { children: 'children', label: 'name' },
      nowDatasourceShow: {},
      databaseList: [],
      dbType: "",
      host: "asasas",
      databaseExpandedKeys: [],
      upgradeInfo: {},
      treeClickCount: 0,
      currentPageList: [],
      DatasourceId:0,
      activePage: '',
      linkList:[],
      queryData:{},
      tmpid:"",
    }
  },
  created () {

    if (localStorage.getItem("font")) {
      this.$store.commit("global/setFont", parseInt(localStorage.getItem("font")))
    }
    if (localStorage.getItem("color")) {
      this.$store.commit("global/setColor", localStorage.getItem("color"))
    }
  if(this.$route.fullPath.indexOf("manage") != -1){
    this.showactive=false;
  }else{
    this.showactive=true;
    this.nowClickPath = { sourceId: this.choiceDatasourceId, host: "dsadsa", dbName: "sda", tableName: "sad", dbType: "sdaaaa", tableType: "saddd" ,key:'pane-6f850ea9-a1df-45ac-9850-22deae062d8a'};
    this.addtables({
      query: this.nowClickPath,
      content: "sqlexcuter",
      name:"SQL 编辑器",
      viewType:1
    });
    this.activePage='pane-6f850ea9-a1df-45ac-9850-22deae062d8a';
  }


  },
  computed: {

    fullscreen () {
      return this.$store.state.global.fullscreen;
    },

  },
  mounted: function () {
    this.loadDatasourceList();
    this.dragControllerDiv();

  },
  methods: {
    uuid() {
      var s = [];
      var hexDigits = "0123456789abcdef";
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = "-";
      var uuid = s.join("");
      return uuid;
    },
    removePageTab(key){
      if (this.currentPageList.length === 1) {
        this.$message.warning("这是最后一页，不能再关闭了啦");
        return;
      }
      this.currentPageList = this.currentPageList.filter((item) => item.query.key !== key);
      let index = this.linkList.indexOf(key);
      this.linkList = this.linkList.filter((item) => item !== key);
      index = index >= this.linkList.length ? this.linkList.length - 1 : index;
      console.info(this.linkList[index])
      this.activePage = this.linkList[index];
    },
    pageGo(path) {
      this.$router.push('/' + path)
    },
    selectFunc(value) {
      this.selectValue2 = value
      console.log(this.selectValue)
      console.log(this.selectValue2)
    },
    setcongig(config){
      console.info("aaaaaaaaaaaaaaaaa")
      debugger
      this.$refs.$sqlExcuter.setcongig(5)
    },
    addtables(config) {
     if(this.currentPageList.length<13){
       console.info(config)
       this.currentPageList.push(config);
       this.linkList.push(config.query.key)
       this.activePage=config.query.key;
     }else{
       this.$message.warning("标签页打开到最大值");
     }

    },
    dragControllerDiv: function () {
      var resize = document.getElementsByClassName('resize');
      var left = document.getElementsByClassName('left');
      var mid = document.getElementsByClassName('mid');
      var box = document.getElementsByClassName('box');
      for (let i = 0; i < resize.length; i++) {
        // 鼠标按下事件
        resize[i].onmousedown = function (e) {
          //颜色改变提醒
          resize[i].style.background = '#818181';
          var startX = e.clientX;
          resize[i].left = resize[i].offsetLeft;
          // 鼠标拖动事件
          document.onmousemove = function (e) {
            var endX = e.clientX;
            var moveLen = resize[i].left + (endX - startX); // （endx-startx）=移动的距离。resize[i].left+移动的距离=左边区域最后的宽度
            var maxT = box[i].clientWidth - resize[i].offsetWidth; // 容器宽度 - 左边区域的宽度 = 右边区域的宽度

            if (moveLen < 32) moveLen = 32; // 左边区域的最小宽度为32px
            if (moveLen > maxT - 150) moveLen = maxT - 150; //右边区域最小宽度为150px

            resize[i].style.left = moveLen; // 设置左侧区域的宽度

            for (let j = 0; j < left.length; j++) {
              left[j].style.width = moveLen + 'px';
              mid[j].style.width = (box[i].clientWidth - moveLen - 10) + 'px';
            }
          };
          // 鼠标松开事件
          document.onmouseup = function (evt) {
            //颜色恢复
            resize[i].style.background = '#d6d6d6';
            document.onmousemove = null;
            document.onmouseup = null;
            resize[i].releaseCapture && resize[i].releaseCapture(); //当你不在需要继续获得鼠标消息就要应该调用ReleaseCapture()释放掉
          };
          resize[i].setCapture && resize[i].setCapture(); //该函数在属于当前线程的指定窗口里设置鼠标捕获
          return false;
        };
      }
    },




    changePage(key) {
      this.activePage = key.name;
    },
    allowDrop (draggingNode, dropNode, type) {
      return false;
    },
    allowDrag (draggingNode) {
      if (draggingNode.data.type !== 2 && draggingNode.data.type !== 3) {
        return true;
      }
      else {
        return false;
      }
    },
    handleDragStart (node, ev) {
      console.log('drag start', node);
    },
    handleDragEnd (node, ev) {
      if (this.$route.path === '/data/executor') {
        // this.$children[0].$children[1].$children[0].$children[0]

        var index =this.linkList.indexOf(this.activePage);
        console.info(index)
        let that = this.$refs.$sqlExcuter[index];
        that.sqlExecutorEditor =that.initAceEditorPage("sqlExecutorEditor", 30);
        console.info(that.sqlExecutorEditor)
        let cursorPosition = that.sqlExecutorEditor.getCursorPosition();
        that.sqlExecutorEditor.setFontSize(this.$store.getters['global/getFont']);
        let sql = "";
        if (node.data.type == 1 || node.data.type == 5) {
          sql = node.data.name;
        } else if (node.data.type == 4) {
          sql = node.parent.data.dbName + '.' + node.data.name;
        }
        that.sqlExecutorEditor.session.insert(cursorPosition, sql);
      }

      console.log('drag end', node);
    },
    loadNode (node, resolve) {
      if (node.level === 0) {
        return resolve([{ name: 'region1' }, { name: 'region2' }]);
      }
      if (node.level > 3) return resolve([]);

      var hasChild;
      if (node.data.name === 'region1') {
        hasChild = true;
      } else if (node.data.name === 'region2') {
        hasChild = false;
      } else {
        hasChild = Math.random() > 0.5;
      }

      setTimeout(() => {
        var data;
        if (hasChild) {
          data = [{
            name: 'zone' + this.count++
          }, {
            name: 'zone' + this.count++
          }];
        } else {
          data = [];
        }

        resolve(data);
      }, 500);
    },
    userSettingDropdown (command) {
      console.log("command:" + command);
      if (command == 'userSignOut') {
        this.userSignOut();
      } else if (command == 'aboutDoc') {
        this.aboutDialogVisible = true;
      } else if (command == 'myInfo') {
        this.$router.push({ path: '/user/myInfo' }).catch(err => { err })
      } else if (command == 'console') {
        window.location = process.env.VUE_APP_BASE_API;
      } else {
        this.$message.warning("功能暂未开放");
      }
    },
    userSignOut () {
      userApi.userLogout().then(() => {
        location.reload();
      });
    },
    getSelfUserInfo () {
      userApi.getSelfUserInfo().then(json => {
        this.userSelfInfo = json.data;
      });
    },
    sourceGroupChangeEvents () {
      let datasourceOptions = [];
      for (let i = 0; i < this.datasourceList.length; i++) {
        let item = this.datasourceList[i];
        if (!this.choiceDatasourceGroup || this.choiceDatasourceGroup == item.groupName) {
          datasourceOptions.push({ label: item.name, value: item.id });
        }
      }
      this.datasourceOptions = datasourceOptions;
    },
    datasourceChangeEvents () {
      this.nowDatasourceShow = this.choiceDatasourceId;
      for (var i = 0; i < this.datasourceList.length; i++) {
        if (this.datasourceList[i].id == this.choiceDatasourceId) {
          this.host = this.datasourceList[i].name;
          this.datasourceOptions.select = this.datasourceList[i].name;
          if (this.host.startsWith("oracle")) {
            this.dbType = "oracle.jdbc.driver.OracleDriver"
          } else {
            this.dbType = this.datasourceList[i].driverClassName;
          }
          if(this.$refs.$sqlExcuter.length>0){
            this.$refs.$sqlExcuter[  this.$refs.$sqlExcuter.length-1].loadEditorDataPage(this.choiceDatasourceId);
            break;
          }
          this.$refs.$sqlExcuter.loadEditorDataPage(this.choiceDatasourceId);
          break;
        }
      }
      this.loadDatabaseList(this.choiceDatasourceId);
      console.info("点击后的数据源为"+this.choiceDatasourceId)
    },
    handleNodeClick (node) {
      // 执行器里面点击库表不跳转页面
      // if (this.$router.currentRoute.path == "/data/executor") {
      //     return;
      // }
      //记录点击次数

      this.treeClickCount++;
      console.log("点击节点aaaaaaaaaaa：", this.treeClickCount);
      //单次点击次数超过2次不作处理,直接返回,也可以拓展成多击事件
      if (this.treeClickCount >= 2) {
        return;
      }
      //计时器,计算300毫秒为单位,可自行修改
      this.timer = window.setTimeout(() => {
        if (this.treeClickCount == 1) {
          //把次数归零
          this.treeClickCount = 0;
          //单击事件处理
          // this.console('单击事件,可在此处理对应逻辑')
          this.tmpid=this.choiceDatasourceId;
        } else if (this.treeClickCount > 1) {
          //把次数归零
          this.treeClickCount = 0;
          //双击事件
          if (node.type === 4) {
            this.choiceDatasourceId=this.tmpid;
            var kk=this.uuid();
            this.queryData={"sourceId": this.choiceDatasourceId,"host":node.host,"dbName":node.dbName,"tableName":node.name,"tableType":node.tableType,dbType: this.dbType,tableName: node.name,"view":this}
            this.nowClickPath = { sourceId: this.choiceDatasourceId, host: node.host, dbName: node.dbName, tableName: node.name, dbType: this.dbType, tableType: node.tableType,key: kk,queryData:this.queryData};
            this.addtables({
              path: "/table/info",
              query: this.nowClickPath,
              content: "asasasasa",
              name:node.name,
              viewType:2,
            });
            this.activePage=kk;
          } else if (node.type === 1) {
            console.info("点击库节点")
            var kk=this.uuid();
            this.nowClickPath = { sourceId: this.choiceDatasourceId, dbName: node.dbName, host: node.host,key: kk};
            this.addtables({
              path: "/table/info",
              query: this.nowClickPath,
              content: "asasasasa",
              name:node.name,
              viewType:3,
            });
          }
        }
      }, 300);
      console.info(this.choiceDatasourceId)
    },
    handleNodeExpand (node) {
      if (node.children.length > 0 && node.children[0].needLoad) {
        console.log("加载节点：", node);
        if (node.type == 1) {
          this.loadSchemaContainer(node);
        } else if (node.type == 2) {
          this.loadGetTableList(node, null);
        } else if (node.type == 3) {
          this.loadGetTableList(node, 'VIEW');
        } else if (node.type == 4) {
          this.loadGetTableColumnList(node);
        }
      }
    },
    loadSchemaContainer (node, callback) {
      let pathIndex = [{ label: 'tables', host: this.host, icon: "el-icon-folder-opened", name: "tables", dbName: node.dbName, id: node.id + '_' + 'tables', name: 'tables', type: 2, children: [{ label: '', needLoad: true }] }, { label: 'views', host: this.host, icon: "el-icon-folder-opened", name: "views", name: 'views', id: node.id + '_' + 'views', dbName: node.dbName, type: 3, children: [{ label: '', needLoad: true }] }]
      pathIndex.children = [{ label: '', needLoad: true }];
      node.children = pathIndex;
      if (typeof callback == 'function') {
        callback(pathIndex);
      }
    },
    loadGetTableList (node, type, callback) {
      datasourceApi.tableList({ sourceId: this.choiceDatasourceId, dbName: node.dbName }).then(json => {
        let pathIndex = [];
        let result = json.data || [];
        for (let i = 0; i < result.length; i++) {
          let item = {
            id: node.id + "_" + result[i].tableName,
            name: result[i].tableName, type: 4,
            dbName: node.dbName,
            host: this.host,
            comment: result[i].tableComment,
            icon: "el-icon-document",
            tableType: result[i].tableType,
          };
          item.children = [{ label: '', needLoad: true }];// 初始化一个对象，点击展开时重新查询加载
          pathIndex.push(item);
        }
        if (type !== null) {
          pathIndex = pathIndex.filter(row => row.tableType === 'VIEW')
        } else {
          pathIndex = pathIndex.filter(row => row.tableType != 'VIEW')
        }
        node.children = pathIndex;
        if (typeof callback == 'function') {
          callback(pathIndex);
        }
      });
    },
    loadGetTableColumnList (node, callback) {
      let vueQueryParam = { sourceId: this.choiceDatasourceId, dbName: node.dbName, tableName: node.name };
      datasourceApi.tableColumnList(vueQueryParam).then(json => {
        let columnList = json.data.columnList || [];
        for (let i = 0; i < columnList.length; i++) {
          columnList[i].id = node.id + "_" + columnList[i].name;
          columnList[i].comment = columnList[i].type;
          columnList[i].type = 5;
          columnList[i].icon = "el-icon-mobile";
          if (columnList[i].ispramary) {
            columnList[i].comment += ' (primary)'
          }
        }
        node.children = columnList
        this.columnList = columnList;
        if (typeof callback == 'function') {
          callback(columnList);
        }
      })
    },
    loadDatasourceList () {
      datasourceApi.datasourceList({}).then(json => {
        this.datasourceList = json.data || [];
        let datasourceOptions = [];
        for (let i = 0; i < this.datasourceList.length; i++) {
          let item = this.datasourceList[i];
          datasourceOptions.push({ label: item.name, value: item.id });
        }
        this.datasourceOptions = datasourceOptions;
        let datasourceGroupList = [];
        this.datasourceList.filter(item => !!item.groupName).forEach(item => datasourceGroupList.push(item.groupName || ''));
        this.datasourceGroupList = Array.from(new Set(datasourceGroupList));
      });
    },
    loadDatabaseList (sourceId) {
      return new Promise((resolve, reject) => {
        this.databaseList = [];
        datasourceApi.databaseList({ sourceId: sourceId }).then(json => {
          let result = json.data || [];
          let pathIndex = [];
          for (var i = 0; i < result.length; i++) {
            this.host = this.$refs.itemSelect.selectedLabel
            let item = {
              id: this.host + "_" + result[i].dbName,
              dbName: result[i].dbName,
              host: this.host,
              icon: "el-icon-coin",
              name: result[i].dbName, type: 1
            };
            item.children = [{ label: '', needLoad: true }];// 初始化一个对象，点击展开时重新查询加载
            pathIndex.push(item);
          }
          this.databaseList = pathIndex;
          resolve();
        });
      });
    },
    initLoadDataList (param) {
      if (this.databaseList.length > 0) {
        return;
      }
      this.choiceDatasourceId = parseInt(param.sourceId);
      this.loadDatabaseList(param.sourceId, param.host).then(() => {
        this.databaseExpandedKeys = [param.host];
      });
    }
  }
}
</script>

<style>
html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
}
.box {
  width: 100%;
  height: 100%;
  overflow: hidden;
  box-shadow: -1px 9px 10px 3px rgba(0, 0, 0, 0.11);
}
#app,
.el-container,
.el-menu {
  height: 100%;
}
.el-header {
  background-color: white !important;
}
.database-list-tree {
  background-color: #fafafa;
}
.database-list-tree .el-tree-node > .el-tree-node__children {
  overflow: unset;
}
.header-right-user-name {
  color: #fff;
  padding-right: 5px;
}
.el-menu-vertical {
  border-right: 0;
  background: #fafafa;
}
.el-menu-vertical .el-menu {
  background: #fafafa;
}
.el-header {
  background-color: #409eff;
  color: #333;
  line-height: 40px;
  text-align: right;
  height: 40px !important;
}

.el-tree-node.is-current > .el-tree-node__content {
  background-color: #c2d6ea !important;
}
.el-tree-node:focus>.el-tree-node__content {
  background-color: #fff;
  color: #409eff;
}
/*.el-tree-node:focus>.el-icon-document {*/
/*  background-color: #fff;*/
/*  color: red;*/
/*}*/
  .is-expanded >div>span.el-icon-coin:before {
    color: #409eff;
  }
.is-expanded >div>span.el-icon-folder-opened:before{
  color: #409eff;
}
.is-expanded >div>span.el-icon-document:before{
  color: #409eff;
}
.resize {
  cursor: col-resize;
  float: left;
  position: relative;
  top: 45%;
  background-color: #d6d6d6;
  border-radius: 5px;
  margin-top: -10px;
  width: 10px;
  height: 50px;
  background-size: cover;
  background-position: center;
  /*z-index: 99999;*/
  font-size: 32px;
  color: white;
}
/*拖拽区鼠标悬停样式*/
.resize:hover {
  color: #444444;
}
.left {
  width: calc(32% - 10px);  /*左侧初始化宽度*/
  height: 100%;
  background: #FFFFFF;
  float: left;
}
.right {
  float: left;
  width: 68%;   /*右侧初始化宽度*/
  height: 100%;
  background: #fff;
  box-shadow: -1px 4px 5px 3px rgba(0, 0, 0, 0.11);
}
::-webkit-scrollbar {
  width : 10px;
  height: 10px;
}
::-webkit-scrollbar-thumb {
  border-radius   : 10px;
  background-color: skyblue;
  background-image: -webkit-linear-gradient(
          45deg,
          rgba(255, 255, 255, 0.2) 25%,
          transparent 25%,
          transparent 50%,
          rgba(255, 255, 255, 0.2) 50%,
          rgba(255, 255, 255, 0.2) 75%,
          transparent 75%,
          transparent
  );
}
::-webkit-scrollbar-track {
  box-shadow   : inset 0 0 5px rgba(0, 0, 0, 0.2);
  background   : #ededed;
  border-radius: 10px;
}
.my-custom-cls{
  position: relative;
}
  .my-custom-cls > .el-tabs__header.is-top{
    position: absolute;
    top: 62px;
  }
  .el-tabs--card>.el-tabs__header .el-tabs__nav{
    margin-left: 7px;
  }
</style>
